''''
描述：Flask中数据库的操作。
     pip install Flask-SQLAlchemy
'''''
from flask import Flask, request, make_response, render_template, session
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.secret_key = "flask666" # 用来加密的密钥
ctx = app.app_context() # 创建app上下文，通过上下文可以访问Flask中全局的对象
ctx.push() # 将上下文推送到堆栈中
# 数据库的类型+操作数据库的包://用户名:密码主机地址:端口号/数据库名字
# 数据库是已经存在的
uri ="mysql+pymysql://root:123456@127.0.0.1:3306/flask_test"
app.config['SQLALCHEMY_DATABASE_URI'] = uri
db = SQLAlchemy(app) # 创建一个操作数据库的对象

# 一个类对应数据库中的一个表
class Member(db.Model):
    __tablename__ = "Member" # 设置表名
    phone = db.Column(db.String(11), primary_key=True) # 定义字段
    pwd = db.Column(db.String(18))
    amount = db.Column(db.Float) # 浮点数

# http://127.0.0.1:5000/register?mobilephone=13812345678&pwd=123456
# get方法
@app.route("/register", methods=['GET'])
def register():
    phone = request.args.get('mobilephone') # request.args 获取?后面拼接的参数
    pwd = request.args.get('pwd')
    # 检查输入的数据是否合法
    # 写到数据库
    m = Member(phone=phone, pwd=pwd, amount=0)
    try:
        db.session.add(m)
        db.session.commit()
        return make_response("注册成功")
    except Exception as e:
        return make_response(f"注册失败，用户名或者密码错误，异常信息为：{e}")

@app.route("/login", methods=['POST'])
def login():
    phone = request.form.get('mobilephone')
    pwd = request.form.get('pwd')
    if phone.strip() == "" or pwd.strip() == "":
        return make_response("用户名或密码为空")
    else:
        # 从数据库中查询用户信息
        m = Member.query.filter_by(phone=phone).first()
        if m is None:
            return make_response("用户未注册")
        else:
            if m.pwd == pwd:
                res = make_response("登录成功")
                session["logininfo"] = f"user {phone} is login"
                session["tips"] = "this is a test" # 设置session
                return res
            else:
                return make_response("用户名或密码错误")

# 充值
@app.route("/recharge", methods=['POST'])
def recharge(): # mobilephone=, amount=
    phone = request.form.get('mobilephone')
    amount = request.form.get('amount')
    # 获取session
    a = session.get("logininfo")
    b = session.get("tips")
    # 验证cookie对不对
    if a == f"user {phone} is login" and b == "this is a test":
        pass
    else:
        return make_response("请先登录")

    if phone.strip() == "":
        return make_response("手机号码为空")
    else:
        m = Member.query.filter_by(phone=phone).first()
        if m is None:
            return make_response("用户未注册")
        else:
            if amount.strip() == "" or float(amount) <= 0:
                return make_response("充值金额错误")
            else:
                m.amount += float(amount) # 修改数据
                db.session.commit() # 提交数据
                return make_response("充值成功")
# 提现
@app.route("/withdraw", methods=['POST'])
def withdraw(): # mobilephone=, amount=
    phone = request.form.get('mobilephone')
    amount = request.form.get('amount')

    # 获取session
    a = session.get("logininfo")
    b = session.get("tips")
    # 验证session对不对
    if a == f"user {phone} is login" and b == "this is a test":
        pass
    else:
        return make_response("请先登录")

    if phone.strip() == "":
        return make_response("手机号码为空")
    else:
        m = Member.query.filter_by(phone=phone).first()
        if m is None:
            return make_response("用户未注册")
        else:
            if amount.strip() == "" or float(amount) <= 0:
                return make_response("提现金额错误")
            else:
                if m.amount < float(amount):
                    return make_response("余额不足")
                else:
                    m.amount -= float(amount) # 修改数据
                    db.session.commit() # 提交数据
                    return make_response("提现成功")


@app.route("/index")
def index():
    return render_template("index.html") # 返回一个html的页面

@app.route("/register.html")
def register_html():
    return render_template("register.html") # 返回一个html的页面

@app.route("/login.html")
def login_html():
    return render_template("login.html") # 返回一个html的页面

@app.route("/recharge.html")
def recharge_html():
    return render_template("recharge.html") # 返回一个html的页面

@app.route("/withdraw.html")
def withdraw_html():
    return render_template("withdraw.html") # 返回一个html的页面

@app.route("/logout.html")
def logout_html():
    res = make_response("退出登录成功")
    # 删除session
    session.pop("logininfo") # 删除cookie
    session.pop("tips") # 删除cookie
    return res

if __name__ == '__main__':
    db.drop_all() # 删除所有表
    db.create_all() # 创建所有表
    # 表中添加数据  创建对象时，需要带着参数名
    m1 = Member(phone="15592215821", pwd="123456", amount=100000000)
    m2 = Member(phone="15012345678", pwd="123456", amount=2000)
    m3 = Member(phone="13012345678", pwd="123456", amount=500.5)
    db.session.add(m1) # 添加一个
    db.session.add_all([m2, m3]) # 添加多个
    db.session.commit() # 提交

    app.run(host='0.0.0.0', port=5000, debug=True)
